package com.wh1200.mybatis.xmlless.model.dto

import com.wh1200.mybatis.xmlless.annotations.JoinObject
import com.wh1200.mybatis.xmlless.model.ObjectJoinInfo
import com.wh1200.mybatis.xmlless.model.Properties
import com.wh1200.mybatis.xmlless.model.TypeInfo
import com.wh1200.mybatis.xmlless.model.base.BaseJoinObjectProvider
import com.wh1200.mybatis.xmlless.util.TableInfoProvider
import net.sf.jsqlparser.parser.CCJSqlParserUtil
import net.sf.jsqlparser.schema.Column

/**
 * @author 吴昊
 * @date 2024/01/19
 * @version 1.0
 * @since v4.0.0
 */
class JavaFieldJoinObjectProvider(
    private val joinObject: JoinObject,
    private val selectedProperties: List<String>,
    private val property: String,
    private val genericType: TypeInfo
) : BaseJoinObjectProvider {

  override fun resolve(): ObjectJoinInfo {
    val xmllessTableInfo = TableInfoProvider.getOrInitXmllessTableInfo(genericType.realType)
    val joinOnTargetProperty = joinObject.joinOnTargetProperty.ifBlank {
      xmllessTableInfo.keyProperty ?: error("持久化对象${genericType.realType.getClassName()}缺少主键字段")
    }
    val targetTableName = resolveJoinTableName(
        joinObject.joinOnThisProperty,
        joinObject.alias, xmllessTableInfo
    )
    return ObjectJoinInfo(
        genericType.realType.getClassName(),
        xmllessTableInfo,
        Properties(selectedProperties),
        targetTableName,
        joinObject.joinType,
        Column(joinObject.joinOnThisProperty),
        CCJSqlParserUtil.parseExpression(joinOnTargetProperty),
        associationPrefix = property + "_",
        javaType = genericType
    )
  }

  override fun getAlias(): String {
    return joinObject.alias
  }


}
